﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ActivitiesControl.GUI.Silverlight.Services;
using ActivitiesControl.GUI.Silverlight.RemoteServices;
using System.ComponentModel;
using ActivitiesControl.GUI.Silverlight.Utils;
using ActivitiesControl.GUI.Silverlight.Views;

namespace ActivitiesControl.GUI.Silverlight
{
	public partial class Activities
		: Page
	{
		public Activities()
		{
			InitializeComponent();
			Loaded += new RoutedEventHandler(MainPage_Loaded);
		}

		void MainPage_Loaded(object sender, RoutedEventArgs e)
		{
			Service = ServiceLocator.Instance.Service;
			LoadRemoteObjects();
			InitSearchObjects();
			InitFormObjects();
			Message.Show("Bem-vindo(a) ao sistema de controle de atividades.");
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			base.OnNavigatedTo(e);
		}

		private void SaveButton_Click(object sender, RoutedEventArgs e)
		{
			Service.SaveActivityCompleted -= new EventHandler<AsyncCompletedEventArgs>(service_SaveActivityCompleted);
			Service.SaveActivityCompleted += new EventHandler<AsyncCompletedEventArgs>(service_SaveActivityCompleted);
			
			int? activityId = null;

			if (CurrentActivity != null)
				activityId = CurrentActivity.Id;

			int projectId = ((Project)ProjectsComboBoxForm.SelectedItem).Id;

			Service.SaveActivityAsync(
				activityId, 
				DescriptionTextBox.Text, 
				ActivityTypeAutoCompleteBox.Text, 
				Convert.ToInt32(HoursTextBlock.Text), 
				ActivityDateDatePicker.SelectedDate.Value, 
				projectId, 
				LoggedUser.Instance.User.Id);

			SetPageForCreation();
		}

		private void DeleteButton_Click(object sender, RoutedEventArgs e)
		{
			if (MessageBox.Show("Confirma a exclusão dessa atividade?", "Exclusão", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
			{
				if (CurrentActivity == null)
					return;

				Service.ExcludeActivityCompleted -= new EventHandler<AsyncCompletedEventArgs>(service_ExcludeActivityCompleted);
				Service.ExcludeActivityCompleted += new EventHandler<AsyncCompletedEventArgs>(service_ExcludeActivityCompleted);

				Service.ExcludeActivityAsync(CurrentActivity.Id);

				SetPageForCreation();
			}
		}

		private void NewButton_Click(object sender, RoutedEventArgs e)
		{
			SetPageForCreation();
		}

		void service_ExcludeActivityCompleted(object sender, AsyncCompletedEventArgs e)
		{
			Message.Show("Atividade excluída.", e);
		}

		void service_SaveActivityCompleted(object sender, AsyncCompletedEventArgs e)
		{
			Message.Show("Atividade salva.", e);
		}

		private ActivitiesControlServicesClient Service { get; set; }
		
		private Activity CurrentActivity { get; set; }

		#region Service Objects
		private IList<Customer> customersForm = null;
		private IList<Project> projectsForm = null;

		private IList<Customer> customersSearch = null;
		private IList<Project> projectsSearch = null;

		private bool AreRemoteObjectsLoaded
		{
			get { return customersSearch != null && projectsForm != null && customersSearch != null && projectsSearch != null; }
		}
		void LoadRemoteObjects()
		{
			LoadRemoteObjectsForm();
			LoadRemoteObjectsSearch();
		}
		void LoadRemoteObjectsForm()
		{
			Service.GetCustomersForFormCompleted += delegate(object sender, GetCustomersForFormCompletedEventArgs e)
			{
				customersForm = e.Result;

				Service.GetProjectsForFormCompleted += delegate(object sender2, GetProjectsForFormCompletedEventArgs e2)
				{
					if (projectsForm == null)
						projectsForm = e2.Result;
					else
						foreach (var item in e2.Result)
							if (!projectsForm.Contains(item))
								projectsForm.Add(item);


					Customer selectedCustomer = CustomersComboBoxForm.SelectedItem as Customer;

					Service.GetActivityTypesForFormAsync(selectedCustomer.Id);

					ProjectsComboBoxForm.ItemsSource = from p in projectsForm where p.CustomerId.Equals(selectedCustomer.Id) select p;

					if (ProjectsComboBoxForm.Items.Count > 0)
						ProjectsComboBoxForm.SelectedIndex = 0;
				};

				foreach (var item in customersForm)
				{
					Service.GetProjectsForFormAsync(item.Id);
				}

				CustomersComboBoxForm.ItemsSource = customersForm;

				if (CustomersComboBoxForm.Items.Count > 0)
				{
					CustomersComboBoxForm.SelectedIndex = 0;
				}
			};

			Service.GetCustomersForFormAsync(LoggedUser.Instance.User.Id);
		}
		void LoadRemoteObjectsSearch()
		{
			Service.GetCustomersForSearchFilterCompleted += delegate(object sender, GetCustomersForSearchFilterCompletedEventArgs e)
			{
				customersSearch = e.Result;

				Service.GetProjectsForSearchFilterCompleted += delegate(object sender2, GetProjectsForSearchFilterCompletedEventArgs e2)
				{
					if (projectsSearch == null)
						projectsSearch = e2.Result;
					else
						foreach (var item in e2.Result)
							if (!projectsSearch.Contains(item))
								projectsSearch.Add(item);


					Customer selectedCustomer = CustomersComboBoxSearch.SelectedItem as Customer;

					ProjectsComboBoxSearch.ItemsSource = from p in projectsSearch 
														 where p.CustomerId.Equals(selectedCustomer.Id) || p.CustomerId.Equals(0) 
														 select p;

					if (ProjectsComboBoxSearch.Items.Count > 0)
						ProjectsComboBoxSearch.SelectedIndex = 0;
				};

				foreach (var item in customersSearch)
				{
					Service.GetProjectsForSearchFilterAsync(item.Id);
				}

				CustomersComboBoxSearch.ItemsSource = customersSearch;

				if (CustomersComboBoxSearch.Items.Count > 0)
				{
					CustomersComboBoxSearch.SelectedIndex = 0;
				}
			};

			Service.GetCustomersForSearchFilterAsync(LoggedUser.Instance.User.Id);
		} 
		#endregion

		#region Search
		void InitSearchObjects()
		{
			StartDatePickerSearch.SelectedDate = DateTime.Now.AddMonths(-1);
			EndDatePickerSearch.SelectedDate = DateTime.Now;

			Service.GetActivitiesCompleted -= new EventHandler<GetActivitiesCompletedEventArgs>(service_GetActivitiesCompleted);
			Service.GetActivitiesCompleted += new EventHandler<GetActivitiesCompletedEventArgs>(service_GetActivitiesCompleted);
		}
		void service_GetActivitiesCompleted(object sender, GetActivitiesCompletedEventArgs e)
		{
			ActivitiesDataGrid.ItemsSource = e.Result;
		}
		void CustomersComboBoxSearch_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			BindProjectsSearch();
		}
		void SearchButton_Click(object sender, RoutedEventArgs e)
		{
			if (StartDatePickerSearch.SelectedDate.HasValue && EndDatePickerSearch.SelectedDate.HasValue)
			{
				Service.GetActivitiesAsync(
					LoggedUser.Instance.User.Id,
					StartDatePickerSearch.SelectedDate.Value,
					EndDatePickerSearch.SelectedDate.Value,
					((Customer)CustomersComboBoxSearch.SelectedItem).Id,
					((Project)ProjectsComboBoxSearch.SelectedItem).Id);
			}
		}
		void BindCustomersSearch()
		{
			CustomersComboBoxSearch.ItemsSource = customersSearch;
			if (CustomersComboBoxSearch.Items.Count > 0)
				CustomersComboBoxSearch.SelectedIndex = 0;
		}
		void BindProjectsSearch(Project selectedProject)
		{
			Customer selectedCustomer = CustomersComboBoxSearch.SelectedItem as Customer;

			if (selectedCustomer != null && projectsSearch != null)
			{
				ProjectsComboBoxSearch.ItemsSource = from p in projectsSearch
												   where p.CustomerId.Equals(selectedCustomer.Id) || p.CustomerId.Equals(0)
												   select p;

				if (selectedProject != null)
					ProjectsComboBoxSearch.SelectedItem = selectedProject;
				else if (ProjectsComboBoxSearch.Items.Count > 0)
					ProjectsComboBoxSearch.SelectedIndex = 0;
			}
		}
		void BindProjectsSearch()
		{
			BindProjectsSearch(null);
		}
		#endregion

		void ActivitiesDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			CurrentActivity = ActivitiesDataGrid.SelectedItem as Activity;
			SetPageForEdition();
		}

		#region Activity Maintenance
		void InitFormObjects()
		{
			Service.GetActivityTypesForFormCompleted -= new EventHandler<GetActivityTypesForFormCompletedEventArgs>(service_GetActivityTypesForFormCompleted);
			Service.GetActivityTypesForFormCompleted += new EventHandler<GetActivityTypesForFormCompletedEventArgs>(service_GetActivityTypesForFormCompleted);
			ActivityDateDatePicker.SelectedDate = DateTime.Now;
		}
		void service_GetActivityTypesForFormCompleted(object sender, GetActivityTypesForFormCompletedEventArgs e)
		{
			ActivityTypeAutoCompleteBox.ItemsSource = e.Result;
		}
		void CustomersComboBoxForm_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			BindProjectsForm();

			Customer selectedCustomer = CustomersComboBoxForm.SelectedItem as Customer;

			if (selectedCustomer != null)
				Service.GetActivityTypesForFormAsync(selectedCustomer.Id);
		}
		void BindCustomersForm()
		{
			CustomersComboBoxForm.ItemsSource = customersForm;
			if (CustomersComboBoxForm.Items.Count > 0)
				CustomersComboBoxForm.SelectedIndex = 0;
		}
		void BindProjectsForm()
		{
			Customer selectedCustomer = CustomersComboBoxForm.SelectedItem as Customer;

			if (selectedCustomer != null && projectsForm != null)
			{
				ProjectsComboBoxForm.ItemsSource = from p in projectsForm
												   where p.CustomerId.Equals(selectedCustomer.Id)
												   select p;

				if (ProjectsComboBoxForm.Items.Count > 0)
					ProjectsComboBoxForm.SelectedIndex = 0;
			}
		}
		#endregion

		void SetPageForEdition()
		{
			if (CurrentActivity == null)
				return;

			DeleteButton.IsEnabled = true;
			
			CustomersComboBoxForm.SelectedItem = CurrentActivity.Project.Customer;
			ProjectsComboBoxForm.SelectedItem = CurrentActivity.Project;
			HoursSlider.Value = CurrentActivity.EffortHours;
			DescriptionTextBox.Text = CurrentActivity.Description;
			ActivityTypeAutoCompleteBox.Text = CurrentActivity.ActivityType;
			ActivityDateDatePicker.SelectedDate = new DateTime(CurrentActivity.Date.Year, CurrentActivity.Date.Month, CurrentActivity.Date.Day);

			Message.Show("Edite a atividade selecionada.");
		}
		void SetPageForCreation()
		{
			CurrentActivity = null;

			DeleteButton.IsEnabled = false;

			CustomersComboBoxForm.SelectedIndex = 0;
			ProjectsComboBoxForm.SelectedIndex = 0;
			HoursSlider.Value = 8;
			DescriptionTextBox.Text = string.Empty;
			ActivityTypeAutoCompleteBox.Text = string.Empty;
			ActivityDateDatePicker.SelectedDate = DateTime.Now;

			Message.Show("Crie uma nova atividade.");
		}
	}
}